package com.onion.utils.support.counter;

/**
 * 步步高计时器
 * @param <T>
 */
public class StepCounter<T> {

    private T[] timer;
    private int postion = 0;
    private Object LOCK = new Object();

    private StepCounter(){}

    public static <T> StepCounter instance(T[] timer){
        StepCounter<T> circleCounter = new StepCounter<>();
        circleCounter.timer = timer;
        return circleCounter;
    }

    /**
     * 获取当前
     * @return
     */
    public T getAndNext(){
        int curPostion = postion;
        if(curPostion < timer.length){
            this.next();
            return timer[curPostion];
        }else{
            throw new RuntimeException("Postion非法:" + curPostion);
        }
    }

    /**
     * 获取下一个
     * @return
     */
    public T next(){
        synchronized (LOCK){
            if(postion < timer.length-1){
                return timer[++postion];
            }else{
                postion = timer.length-1;
                return timer[postion];
            }
        }
    }

    /**
     * 重置计时器
     */
    public void reset(){
        synchronized (LOCK){
            this.postion = 0;
        }
    }

}